<template>
	<view>
		<Navbar></Navbar>
		<view class="u-m-t-28">
			<Info :data="detail" @onOperateDemand="onOperateDemand"></Info>
			<view class="u-m-b-30"></view>
			<TalkList v-if="chatList.records && chatList.records.length > 0 && handleGetUserId()"
				:demandOrSupply="demandOrSupply" @leaveMessage="handleLeaveMessage" :chatList="chatList"></TalkList>

			<!-- 推荐需求 -->
			<view class="u-m-t-30 u-back-white" v-if="recommendList.length > 0">
				<view class="u-flex u-p-t-20 u-p-b-20 u-p-l-30 u-p-r-30 u-line-bottom">
					<u-icon name="more-circle-fill" color="#fb6316" size="36"></u-icon>
					<view class="u-color-puce u-font-34 u-font-bold u-m-l-10">更多求助</view>
				</view>
				<view class="u-flex u-p-t-20 u-p-b-20 u-p-l-30 u-p-r-30 u-line-bottom" v-for="item in recommendList"
					:key="item.id" @click="goDemandDetail(item.id)">
					<u-image class="u-m-r-20" width="150rpx" height="150rpx" border-radius="10" :src="item.img[0]" v-if="item.img[0]"></u-image>
					<view class="u-flex-1 u-flex-col u-row-between" style="height: 150rpx;">
						<view class="u-font-26 u-ellipsis-two u-font-bold">{{ item.title}}</view>
						<view class="u-font-24 u-color-gray">
							<span>求助量：</span>
							<span>{{item.num}}</span>
						</view>
						<view class="u-flex u-row-between u-font-24 u-color-gray">
							<view class="u-flex">
								<u-icon name="clock-fill" size="30"></u-icon>
								<view class="u-m-l-10">{{item.audit_time}}</view>
							</view>
							<view class="u-flex">
								<u-icon name="eye-fill" size="30"></u-icon>
								<view class="u-m-l-10">{{item.visit}}</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		
		<view style="height: 250rpx;" />		
		<Bottom :isShare="true" :isDisable="false" :btnText="bottomText" @confirm="handleIsRegister"></Bottom>
		
		<!-- 对接前提示 -->
		<u-modal v-model="showTips" :show-cancel-button="true" width="500" @confirm="handleMinusIntegral"
			confirm-color="#3070F6FF" :title-style="toastTitle" title="温馨提示">
			<view class="slot-content u-flex-col u-col-center u-font-30 u-row-center">
				<text>发送对接信息即成为对接人</text>
				<text class="u-p-t-20">对接求助将消耗{{ demandIntegral }}积分</text>
			</view>
		</u-modal>
		<!-- 对接内容 -->
		<u-popup v-model="showInputPopup" mode="bottom">
			<view class="u-m-40 u-width-100">
				<view class="u-flex">
					<u-input v-model="sendText" class="demand_input_width" :custom-style="inputCustomStyle" type="textarea"
						:auto-height="true" height="160" :focus="inputFocus" :adjust-position="true" :clearable="false"
						placeholder="请输入你的对接信息" maxlength="2000" />
					<view class="u-flex-col demand_input_operate">
						<text @click="handleSendText" class="u-color-puce">发送</text>
						<text @click="showInputPopup = false" class="u-p-t-40">取消</text>
					</view>
				</view>
				<view style="height: 200rpx;"></view>
			</view>
		</u-popup>
		
		<!-- 结束提示 -->
		<u-modal :show-cancel-button="true" @confirm="onCancelDemand" :show-title="false" confirm-text="确定"
			v-model="endModalData.show">
			<view class="slot-content u-flex-col u-col-center u-font-30 u-row-center">
				<text>求助转为“结束”后，</text>
				<text class="u-p-t-20">将不能接受他人求助申请</text>
			</view>
		</u-modal>
		
		<!-- 通用提示 -->
		<Modal :show="modal.show" :confirmText="modal.confirmText" :modalContent="modal.content"
			:showCancel="modal.showCancel" @cancel="modal.show = false" @confirm="modalConfirm"></Modal>
	</view>
</template>

<script>
	import Navbar from '@/components/Navbar.vue'
	// import ListItem from "@/components/ListItem.vue"
	import TalkList from "@/operate/components/TalkList.vue"
	// import OtherAdvItem from "@/components/OtherAdvItem.vue"
	import Modal from '@/components/Modal.vue'
	import Info from "@/operate/components/Info.vue"
	import Bottom from '@/components/Bottom.vue'
	import {
		getDemandSuppyDetail,
		getDemandSupplyText,
		sendDemandSupplyText,
		getSingleIntegral,
		supplyMinusIntegral,
		supplyUpdateVisitByDemandid,
		shareSupplyQrcodeImg,
		viewAdvert,
		onclick_view,
		getRecommend
	} from "@/network/demand.js"
	import { userInfo } from '@/network/api.js'
	import {
		call,
		InitScene,
		throttle,
		noLoginShare,
		formatRichText
	} from "@/utils/index.js"
	export default {
		components: {
			Navbar,
			Info,
			// ListItem,
			TalkList,
			// OtherAdvItem,
			Modal,
			Bottom
		},
		data() {
			return {
				btnCustomStyle: {
					border: "none"
				},
				customStyle: {
					backgroundColor: "#97999b",
					color: "#fff",
				},
				showTips: false,
				showInputPopup: false,
				toastTitle: {
					fontSize: "30rpx",
					fontWeight: "bold"
				},
				inputCustomStyle: {
					background: "#f5f6f8",
					borderRadius: "20rpx",
					padding: "20rpx"
				},
				imgArr: [],
				detail: {},
				detailList: [],
				sendText: "",
				userid: "",
				demandId: "",
				pid: 0,
				chatList: {},
				demandOrSupply: "supply",
				demandIntegral: "",
				contactsLists: [],
				inputFocus: false,
				userIntegral: "",
				showGoRecharge: false,
				// showSharePopup: true,
				demandTypeObj: {
					demand: "需求",
					supply: "供应",
					financing: "投融资"
				},
				demandAdv: {
					demand: '1',
					supply: "2",
					financing: "3"
				},
				codeDemand: {
					dm: "demand",
					sp: "supply",
					fc: "financing"
				},
				advObj: {},
				content: "当前积分不足，无法对接，请充值后再对接",
				/* 1.7版本 */
				recommendList: [],
				page: 1,
				pageSize: 10,
				finished: "nomore",
				/* 新加入 */
				modal: {
					show: false,
					showCancel: true,
					confirmText: '申请',
					content: ''
				},
				endModalData: {
					id: 0,
					show: false
				},
				bottomText:""
			}
		},
		onLoad(options) {
			if (options.scene) {
				options = {
					...InitScene(options.scene)
				}
			}
			this.userid = uni.getStorageSync("user_id")
			this.demandId = options.id
			this.handleGetDetail(options.id)
			this.handleGetRecommend()
		},
		onShareAppMessage() {
			const imageU = this.detail.img[0] || ""
			return {
				title: `求助sos：${this.detail.title}`,
				imageUrl: imageU,
				path: `/operate/demandDetail/demandDetail?id=${this.demandId}&b=1&iv=${this.userid}`
			}
		},
		onShareTimeline() {
			const imageU = this.detail.img[0] || ""
			return {
				title: `求助sos：${this.detail.title}`,
				imageUrl: imageU,
				query: `id=${this.demandId}&b=1&iv=${this.userid}`
			}
		},
		methods: {
			handleGetAdv() {
				const param = {
					type: 1,
					position: 2,
					type_id: this.detail.type,
					label_id: this.detail.type_label_ids
				}
				viewAdvert(param).then(res => {
					this.advObj = res
					if (res && res.id) {
						const param = {
							type: 1,
							t_id: res.id,
							status: 0,
							user_id: uni.getStorageSync("user_id")
						}
						onclick_view(param).then(() => {})
					}
				})
			},
			handleGetShareImage() {
				if (!uni.getStorageSync("user_id")) {
					noLoginShare()
					return;
				}
				if (uni.getStorageSync("user_status") == 0) {
					this.modal.content = '部分功能需注册解锁，注册后即可体验完整服务'
					this.modal.show = true
				} else {
					const sonParam = {
						type: shareSupplyQrcodeImg,
						param: {
							user_id: this.userid,
							demand_id: this.demandId
						}
					}
					/* 生成海报 */
					this.$refs.shareSon.handleShow(sonParam)
				}
			},
			handleUploadImg() {
				let _this = this
				uni.chooseImage({
					count: 6, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: function(res) {
						_this.imgArr.push(res.tempFilePaths)
						_this.handleUpload(_this.imgArr)
					}
				});
			},
			integralConfirm() {
				uni.navigateTo({
					url: '/pages/scoreList/scoreList'
				})
			},
			async handleMinusIntegral() {
				await supplyMinusIntegral({
					demand_id: this.detail.id,
					user_id: this.userid,
					n_integral: 0
				}).then(() => {
					this.handleGetDetail(this.demandId)
					this.showInputPopup = true
					setTimeout(() => {
						this.inputFocus = true
					}, 500)
				})
			},
			// 获取对接需要的创新点
			handleGetIntegralList() {
				let keyType = "DockingSupply"
				getSingleIntegral({
					key: keyType
				}).then(res => {
					this.demandIntegral = res.data.value
				})
			},
			handleCallPhone() {
				call(this.detail.user_mobile)
			},
			handleIsRegister() {
				if (!uni.getStorageSync("user_id")) {
					uni.showToast({
						icon: "none",
						duration: 2000,
						title: "请先点击下方'前往小程序'方可对接",
					})
					return;
				}
				if (uni.getStorageSync("user_status") == 0) {
					this.modal.content = '部分功能需注册解锁，注册后即可体验完整服务'
					this.modal.show = true
				} else {
					if (this.detail.is_docking == 1) {
						this.showInputPopup = true
						// this.handleCallPhone()
						setTimeout(() => {
							this.inputFocus = true
						}, 500)
					} else {
						// 扣积分
						/* this.showTips = true
						this.handleGetIntegralList() */
						// 不扣积分
						this.handleMinusIntegral()
					}
				}
			},
			handleGetDetail(id) {
				getDemandSuppyDetail({
					uid: this.userid || "49",
					id
				}).then(res => {
					this.handleGetChatList()
					this.detailList = [{
						demandOrSupply: this.demandOrSupply,
						resetName: '求助',
						...res.data,
						type_name: res.data.typename,
					}]
					this.detail = {
						...res.data
					}
					const {
						user_type,
						user_position,
						user_mobile,
						user_name,
						user_id,
						user_head_img,
						user_company,
						address,
						industryname,
					} = res.data

					this.contactsLists = [{
						id: user_id,
						type: user_type,
						head_img: user_head_img,
						name: user_name,
						position: user_position,
						address,
						mobile: user_mobile,
						isf: res.data.is_friend,
						industry_names: [industryname]
					}]
					this.handleGetAdv()
					
					/* 新增底部按钮文本 */
					if((this.detail.demand_status === '3' || this.detail.demand_status === '5') && this.detail.solve_user_id !== this.userid){
						this.bottomText = "该求助已解决/已过期"
					}else if(this.detail.demand_status === '3' && this.detail.solve_user_id === this.userid){
						this.bottomText = "该求助已由您解决"
					}else if(this.detail.demand_status == '4' && this.detail.user_id === this.userid){
						this.bottomText = "您的求助审核未通过"
					}else{
						if(this.detail.demand_status === '0' && this.detail.user_id === this.userid){
							this.bottomText = "您的求助正在审核"
						}else{
							this.bottomText = (this.detail.is_docking == 1 ? '立即留言' : '立即对接')
						}
					}
				})
				supplyUpdateVisitByDemandid({demand_id: id})
			},
			handleUpload(imgList) {
				// 点击上传后循环调用uni.uploadFile ，因微信小程序只支持单文件上传
				imgList.forEach(ele => {
					ele.forEach(item => {
						uni.uploadFile({
							url: 'https://cf.medv.com.cn/api/upload_image', //仅为示例，非真实的接口地址
							filePath: item,
							name: 'file',
							formData: {
								'user': 'test' // 上传附带参数
							},
							success: (uploadFileRes) => {}
						});
					})
				})
			},
			handleGoComplain() {
				if (!uni.getStorageSync("user_id")) {
					uni.showToast({
						icon: "none",
						duration: 2000,
						title: "请先点击下方'前往小程序'方可对接",
					})
					return;
				}
				uni.navigateTo({
					url: `/pages/demandComplain/demandComplain?id=${this.detail.id}`
				})
			},
			handleGetChatList() {
				const param = {
					user_id: this.userid,
					demand_id: this.demandId,
					order: "asc"
				}
				getDemandSupplyText(param).then(res => {
					this.chatList = {
						...res.data,
						is_docking: this.detail.is_docking,
						demand_status: this.detail.demand_status
					}
				})
			},
			handleSendText: throttle(function() {
				const param = {
					user_id: this.userid,
					demand_id: this.demandId,
					content: this.sendText,
					pid: this.pid,
					openid: uni.getStorageSync("openid")
				}
				sendDemandSupplyText(param).then(res => {
					this.handleGetDetail(this.demandId)
					this.showInputPopup = false
					this.handleGetChatList()
					this.sendText = ""
				})
			}, 3000),
			handleGetUserId() {
				return uni.getStorageSync("user_id")
			},
			handleLeaveMessage(pid) {
				this.pid = pid
				this.showInputPopup = true
				setTimeout(() => {
					this.inputFocus = true
				}, 500)
			},
			handleOpenDocument(pdfurl) {
				wx.downloadFile({
					url: pdfurl,
					success: function(res) {
						uni.hideLoading()
						var filePath = res.tempFilePath;
						uni.showLoading({
							title: '正在打开',
							mask: true
						})
						wx.openDocument({
							showMenu: true,
							filePath: filePath,
							success: function(res) {
								uni.hideLoading()
							},
							fail: function(err) {
								uni.hideLoading()
							}
						});
					},
					fail: function(err) {
						uni.hideLoading()
					}
				});
			},
			handleGetRecommend() {
				const params = {
					type: 2,
					id: this.demandId,
					page: this.page,
					limit: this.pageSize
				}
				getRecommend(params).then(res => {
					res.data.map(item => this.recommendList.push(item))
					if (res.length > 0 && res.length == 10) {
						this.finished = 'loading'
					} else {
						this.finished = 'nomore'
					}
				})
			},
			modalConfirm() {
				this.modal.show = false
				uni.navigateTo({
					url: "/pages/register/register"
				})
			},
			goDemandDetail(id){
				uni.navigateTo({
					url: "/operate/demandDetail/demandDetail?id=" + id
				})
			},
			onOperateDemand(val){
				switch(val.type){
					case 1:
					    uni.navigateTo({
					    	url: "/pages/resort/resort?id=" + val.id
					    })
						break;
					case 2:
					    this.endModalData.id = val.id
						this.endModalData.show = true
						break;
				}
			},
			onCancelDemand(){
				this.endModalData.show = false
				uni.navigateTo({
					url: "/operate/endDemand/endDemand?id=" + this.endModalData.id 
				})
			}
		},
		onReachBottom() {
			if (this.finished == 'loading') {
				this.page++
				this.handleGetRecommend()
			}
		}
	}
</script>

<style lang="scss" scoped>
	.slot-content {
		font-size: 28rpx;
		color: $u-content-color;
		padding: 40rpx 0;
	}

	.demand_choose_tab {
		width: 80%;
	}

	.demand_input_width {
		width: 68%;
	}

	.demand_input_operate {
		padding-left: 60rpx;
	}

	::v-deep .u-tag {
		padding: 8rpx 16rpx !important;
		margin-bottom: 10rpx
	}

	.demand_complain {
		width: 60rpx;
	}

	.bottom_style {
		position: fixed;
		bottom: 0;
		height: 170rpx;
		border-radius: 40rpx 40rpx 0px 10rpx;
		padding: 0 30rpx 0 30rpx;
		z-index: 99;
		background-color: #fff;
	}

	.demand_docking {
		width: 80%;
	}

	.demand_docking_button {
		padding-left: 46rpx;
	}
</style>